<template>
  <div class="default-main ba-table-box">
    <div class="block">
      <!-- <el-row justify="space-between">
        <el-card class="top-card">
          <template #header>
            <div class="card-header">
              <el-row align="middle"
                      class="selectBlock">
                <span>统计未处理订单：</span>
                <el-select v-model="curShop"
                           clearable>
                  <el-option v-for="item in shop_arr"
                             :key="item.shop_id"
                             :label="item.shop_name"
                             :value="item.shop_id">
                    <span style="float: left">{{ item.shop_name }}</span>
                    <span style="float: right;color: #909399;font-size: 12px; ">US</span>
                  </el-option>
                </el-select>
              </el-row>
              <el-row class="dateBlock">
                <el-date-picker v-model="dateVal"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                :default-time="defaultTime" />
                <el-button type="primary"
                           class="searchBtn">搜索</el-button>
              </el-row>
            </div>
          </template>
          <div class="card-content">
            <div class="card-row">
              <span>发货预警：<span class="numBox">{{ listCounts.AvailableForPickup }}</span></span>
              <span class="fr">面单超时范围18-24小时</span>
            </div>
            <div class="card-row">
              <span>发货超时：<span class="numBox">{{ listCounts.Delivered }}</span></span>
              <span class="fr">面单超过24小时以上</span>
            </div>
            <div class="card-row">
              <span>物流轨迹预警：<span class="numBox">{{ listCounts.DeliveryFailure }}</span></span>
              <span class="fr">物流轨迹超时范围36-48小时</span>
            </div>
            <div class="card-row">
              <span>物流轨迹超时：<span class="numBox">{{ listCounts.Exception }}</span></span>
              <span class="fr">物流轨迹超过48小时以上</span>
            </div>
            <div class="card-row">
              <span>物流轨迹异常：<span class="numBox">{{ listCounts.Expired }}</span></span>
              <span class="fr">物流轨迹异常</span>
            </div>
            <div class="card-row">
              <span>妥投已超时：<span class="numBox">{{ listCounts.InTransit }}</span></span>
              <span class="fr">物流轨迹超过156小时以上</span>
            </div>
          </div>
        </el-card>

        <el-card class="top-card">
          <template #header>
            <div class="card-header">统计17track状态</div>
          </template>
          <div class="card-content">
            <div class="card-row">
              <span>等待上门取件：<span class="numBox">{{ trackCount.count1 }}</span></span>
              <span class="fr">收到信息，运输商收到下单信息，等待上门取件</span>
            </div>
            <div class="card-row">
              <span>运输过久：<span class="numBox">{{ trackCount.count2 }}</span></span>
              <span class="fr">运输过久，包裹已经运输了很长时间而仍未投递成功</span>
            </div>
            <div class="card-row">
              <span>到达待取：<span class="numBox">{{ trackCount.count3 }}</span></span>
              <span class="fr">
                <el-button plain
                           @click="stateExplanation">状态解释</el-button>
              </span>
            </div>
            <div class="card-row">
              <span>派送途中：<span class="numBox">{{ trackCount.count4 }}</span></span>
              <span class="fr">派送途中，包裹正在投递过程中</span>
            </div>
            <div class="card-row">
              <span>投递失败：<span class="numBox">{{ trackCount.count5 }}</span></span>
              <span class="fr">投递失败，包裹尝试派送但未能成功交付</span>
            </div>
            <div class="card-row">
              <span>异常：<span class="numBox">{{ trackCount.count6 }}</span></span>
              <span class="fr">可能异常，包裹可能被退回</span>
            </div>
          </div>
        </el-card>
      </el-row> -->
      <!-- <el-card class="stepBlock">
        <el-steps :space="300"
                  :active="activeStep"
                  align-center>
          <el-step title="用户下单" />
          <el-step title="发货预警"
                   description="预警18小时以内是否出面单" />
          <el-step title="发货超时"
                   description="24小时以内必须出面单" />
          <el-step title="物流轨迹预警"
                   description="预警36小时以内是否出物流轨迹" />
          <el-step title="物流轨迹超时"
                   description="48小时以内必须出物流轨迹" />
          <el-step title="物流轨迹异常"
                   description="96小时以内物流轨迹是否正常" />
          <el-step title="妥投已超时"
                   description="156小时以内必须妥投" />
        </el-steps>
      </el-card> -->
      <div class="table-block">
        <!-- <div class="txt">筛选</div> -->
        <el-alert class="ba-table-alert"
                  v-if="baTable.table.remark"
                  :title="baTable.table.remark"
                  type="info"
                  show-icon />
        <!-- 表格顶部菜单 -->
        <TableHeader :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
                     :quick-search-placeholder="t('Quick search placeholder', { fields: '订单号' })">
          <template #shop>
            <el-select filterable
                       v-model="baTable.comSearch.form['shop_id']"
                       clearable>
              <el-option v-for="item in shop_arr"
                         :key="item.shop_id"
                         :label="item.shop_name"
                         :value="item.shop_id">
              </el-option>
            </el-select>
          </template>
          <template #orderId>
            <el-input v-model="baTable.comSearch.form['order_id']"
                      :rows="2"
                      type="textarea"
                      placeholder="请输入订单号" />
          </template>
        </TableHeader>

        <!-- <template v-if="baTable.auth('')"> -->

        <!-- </template> -->

        <Table></Table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h, provide, nextTick, onMounted, onBeforeMount } from 'vue'
import { CountUp } from 'countup.js'
import { ElMessage, ElNotification, ElMessageBox, type TabsPaneContext, } from 'element-plus'
import baTableClass from '/@/utils/baTable'
// import PopupForm from './popupForm.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi, fileDownload } from '/@/api/common'
import { fileUpload } from '/@/api/backend/order/orderTrack'
import { useAdminInfo } from '/@/stores/adminInfo'
import Cookies from 'js-cookie'
import { useI18n } from 'vue-i18n'
import { concat } from 'lodash-es'
import { getShopList } from '/@/api/backend/common'

defineOptions({
    name: 'order/orderTrack',
})

const { t } = useI18n()
const state: {
    buttonLoading: boolean
} = reactive({
    buttonLoading: false
})
const activeName = ref('')
const activeStep = ref(0)
const shop_arr = ref([] as any[])
const dateVal = ref('')
const defaultTime = ref<[Date, Date]>([
  new Date(2024, 1, 1, 0, 0, 0),
  new Date(2024, 2, 1, 23, 59, 59),
])
const curShop = ref('')
const listCounts = ref({
    AvailableForPickup: 22,
    Delivered: 45136,
    DeliveryFailure: 21,
    Exception: 324,
    Expired: 1,
    InTransit: 3773,
    InfoReceived: 1709,
    NotFound: 0,
    OutForDelivery: 323
})
const trackCount = ref({
    count1: 169,
    count2: 274,
    count3: 312,
    count4: 0,
    count5: 87,
    count6: 2688
})

const stateExplanation = () => {
    ElNotification({
        title: '详情',
        message: h('span', { style: {color: 'teal',fontStyle: 'italic'} }, '到达待取，包裹已经到达目的地的投递点，需要收件人自取')
    })
}

const adminInfo = useAdminInfo()
let optButtons: OptButton[] = [
    {
        render: 'tipButton',
        name: 'info',
        title: 'Info',
        text:  '轨迹',
        type: 'primary',
        icon: '',
        class: 'newButton',
        disabledTip: false,
        click: (row: TableRow) => {
            console.log('newButton')
        }
    }
]
optButtons = concat(defaultOptButtons(['edit', 'delete']), optButtons) 
optButtons[1].display = (row) => {
    return row.id != adminInfo.id
}

const baTable = new baTableClass(
    new baTableApi('/order/orderTrack/'),
    {
        column: [
            {
                label: '店铺',
                prop:  'shop_id',
                operator: 'LIKE', 
                comSearchRender:'slot',
                comSearchSlotName: 'shop',
                show: false
            },
            {   
                label: '店铺', 
                prop: 'shop_name', 
                align: 'center',
                operator: false
            },
            {   label: '跟踪号', 
                prop: 'tracking_number', 
                align: 'center', 
                operator: 'LIKE', 
                operatorPlaceholder: t('Fuzzy query') 
            },
            { 
                label: '物流状态',
                prop: 'sub_status', 
                align: 'center', 
                render: 'tag',
                replaceValue: { 
                    'Delivered_Other': "交付",
                    'OutForDelivery_Other': "待交付",
                    'InTransit_Other': "在旅途中",
                    'InfoReceived': "信息收到了",
                    'InTransit_PickedUp': "在途中拾取",
                    'Exception_Returning': "异常返回",
                    'DeliveryFailure_InvalidAddress': "配送失败地址无效",
                    'AvailableForPickup_Other': "可接送其他",
                    'DeliveryFailure_NoBody': "交货失败",
                    'DeliveryFailure_Other': "发货失败",
                    'Exception_Returned': "异常返回",
                    'Exception_Other': "其他异常",
                    'Exception_Delayed': "异常延迟",
                    'Exception_NoBody': "例外的人",
                    'Exception_Security': "异常安全的",
                    'InTransit_CustomsReleased': "过境海关放行",
                    'InTransit_Departure': "在旅途中的离职",
                    'InTransit_CustomsProcessing': "过境海关处理",
                    'Exception_Rejected': "异常拒绝",
                },
                operator: false
            },
            // {
            //     label: '订单号',
            //     prop:  'order_id',
            //     operator: 'LIKE', 
            //     align: 'center', 
            //     comSearchRender:'slot',
            //     comSearchSlotName: 'orderId'
            // },
            {
                label: '下单时间',
                prop: 'createtime',
                align: 'center',
                render: 'datetime',
                operator: 'RANGE'
            },
            // {
            //     label: t('Operate'),
            //     align: 'center',
            //     width: '100',
            //     render: 'buttons',
            //     buttons: optButtons,
            //     operator: false
            // }
        ],
        dblClickNotEditColumn: ['all']
    },
    {
        defaultItems: {
            status: '1',
        }
    }
)

provide('baTable', baTable)

baTable.mount()
baTable.getIndex()

// 数字动画效果
const countUpFun = () => {
    nextTick(() => {
        const numBoxs = document.querySelectorAll('.numBox')
        numBoxs.forEach((el:any, i) => {
            const value = el?.innerText
            el.id = `numBox${i}`
            if (value) {
                new CountUp(el.id, parseInt(value), {
                    startVal: 0,
                    duration: 3,
                }).start()
            }
        })
    })
}

const onOrderUpload = (file:any) => {
    let fd = new FormData()
    fd.append('file', file.raw)
    fileUpload(fd).then((res) => {
        if (res.code == 200) {
            ElMessage ({
                type: 'success',
                message: res.msg,
            })
        } else {
            ElMessage ({
                type: 'error',
                message: '上传失败',
            })
        }
    })
}

const handleStatus = (tab: TabsPaneContext) => {
    activeStep.value = Number(tab.props.name)
    baTable.comSearch.form['status'] = tab.props.name
    const comSearchData: Array<any> = baTable.table.filter?.search || [];
    comSearchData.push({
        field: "status",
        val: tab.props.name,
        operator: "",
        render: "",
    })
    baTable.onTableAction('com-search', comSearchData)
}

const exportExcelOperate = () => {
    state.buttonLoading = true
    baTable.table.loading = true
    ElMessageBox.confirm(
        '是否确认导出所有数据项?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        type keymaps = {
            [key: string]: string | number
        }
        const obj:keymaps = {}
        baTable.table.filter?.search!.forEach(v => {
            obj[v.field] = v.val
        }) || []
        // exportExcel('post', obj).then(response => {
        //     fileDownload(response, Cookies.get('filename') || 'file.xlsx')
        // }).catch(err => {
        //     state.buttonLoading = false
        //     baTable.table.loading = false
        // }).finally(() => { 
        //     state.buttonLoading = false
        //     baTable.table.loading = false
        // })
        console.log('exportExcelOperate')
        state.buttonLoading = false
        baTable.table.loading = false
    }).catch(() => {
        state.buttonLoading = false
        baTable.table.loading = false
    })
}

const getShopArr = () => {
    getShopList().then(res => {
        if(res.data && res.data.list.length) {
            shop_arr.value = res.data.list
        }
    })
}

onBeforeMount(() => {
    getShopArr()
})

onMounted(() => {
    countUpFun()
})

</script>

<style scoped lang="scss">
.block{
    // margin: 20px;
    .fr{
        float: right;
    }
    .top-card{
        font-size: 16px;
        width: 49.8%;
        .card-header{
            .el-row{
                margin: 10px 0;
            }
            .dateBlock{
                :deep(.el-date-editor){
                    max-width: 400px;
                }
                .searchBtn{
                    margin-left: 10px;
                }
            }
        }
        .card-content{
            .card-row{
                margin: 16px 0;
            }
            .numBox{
                font-size: 24px;
                vertical-align: middle;
            }
        }
    }
    .stepBlock{
        margin: 5px 0;
    }
    .table-block{
        .txt{
            font-size: 16px;
            background-color: #fff;
            line-height: 3;
            padding: 0 30px;
        }
    }
}
</style>
